//
//  AddDeviceVC.m
//  FishTank
//
//  Created by Scott Zhu on 15/1/4.
//  Copyright (c) 2015年 Scott Zhu. All rights reserved.
//

#import "AddDeviceVC.h"
#import "LANFindServer.h"
#import "DeviceListVC.h"

@interface AddDeviceVC (){
    UIView *_header;
}
@property (strong, nonatomic) LANFindServer *lanFindServer;
@property (strong, nonatomic) NSMutableArray * tempArray;
@end

@implementation AddDeviceVC
@synthesize deviceList = _deviceList;
@synthesize lanFindServer = _lanFindServer;




- (void)viewDidLoad {
    [super viewDidLoad];
    [self _initHeaderView];
    if ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != ReachableViaWiFi)
    {
        UIAlertView *noWiFiAlert = [[UIAlertView alloc] initWithTitle:@"❌请先连接WiFi"
                                                              message:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"确定"
                                                    otherButtonTitles:nil, nil];
        [noWiFiAlert setTag:NO_WIFI_ALERT];
        [noWiFiAlert show];
    }
    
    
    
    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
    id object =  [userDefault objectForKey:SENSEN_DEVICE_AQ];
    
    if (object != nil&&  [object respondsToSelector:@selector(initWithCoder:)]&& [object isKindOfClass:NSData.class]) {
        NSData * customData = (NSData * )object;
        self.tempArray = [NSKeyedUnarchiver unarchiveObjectWithData:customData];
    }
    
    [self.lanFindServer Start];
    __weak typeof (self) weakSelf = self;
    [self.lanFindServer setNewDeviceCallback:^(WifiDevice *obj)
     {
         
         NSLog(@"%@", [obj description]);
         DeviceInfo *deviceInfo = [[DeviceInfo alloc] initWithDid:obj.m_did
                                                       macAddress:obj.m_mac
                                                         password:obj.m_password
                                                               ip:obj.m_lanIp
                                                           isLock:obj.m_lock];
         weakSelf.tempArray  = [NSMutableArray arrayWithCapacity:1];
         if (deviceInfo.did.length > 0 && deviceInfo.password.length > 0 ) {
             //请求列表数据 看是否已经添加到设备列表
             [weakSelf requestDeviceListData:deviceInfo];
         }

         
        }];
    
}

- (void)requestDeviceListData:(DeviceInfo *)deviceInfo{
    
    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
    id object =  [userDefault objectForKey:SENSEN_DEVICE_AQ];
    
    if (object != nil&&  [object respondsToSelector:@selector(initWithCoder:)]&& [object isKindOfClass:NSData.class]) {
        NSData * customData = (NSData * )object;
        self.tempArray = [NSKeyedUnarchiver unarchiveObjectWithData:customData];
     }

    BOOL shouldAdd = [self isThisDeviceExist:deviceInfo];
    
    if(shouldAdd){
        _header.hidden = YES;
        self.tableView.hidden = NO;
        [self.deviceList addObject:deviceInfo];
        [self.tableView reloadData];
    }
    
    
    
}


//这个设备是否存在
- (BOOL)isThisDeviceExist:(DeviceInfo *)deviceInfo{
    
    if(self.tempArray != nil){
        for (DeviceInfo *tempDevice in self.tempArray)
        {
            if ([deviceInfo.did isEqualToString:tempDevice.did])
            {
                deviceInfo.name = tempDevice.name;
                deviceInfo.alreadyExist = YES;
                break;
            }
        }
    }
    
    
    BOOL shoudAdd = YES;
    
    if(self.deviceList != nil){
        
        for (DeviceInfo *tempDevice in self.deviceList)
        {
            if ([deviceInfo.did isEqualToString:tempDevice.did])
            {
                deviceInfo.name = tempDevice.name;
                shoudAdd = NO;
                break;
            }
        }
    }
    
    
    
    return shoudAdd;
}




-(void)viewWillDisappear:(BOOL)animated
{
    [self.lanFindServer Stop];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [self.lanFindServer Stop];
    // Dispose of any resources that can be recreated.
}


- (void)_initHeaderView{
    _header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    _header.backgroundColor = rgba(201, 202, 203, 1);
    [self.view addSubview:_header];
    UILabel *lable = [[UILabel alloc] init];
    [_header addSubview:lable];
    lable.text = @"局域网中的设备";
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_header).offset(20);
        make.top.equalTo(_header).offset(0);
        make.bottom.equalTo(_header).offset(0);
        make.width.equalTo(@200);
    }];
    
    _header.hidden = NO;
    _tableView.hidden = YES;
}




#pragma -mark- Custom Methods
-(BOOL)deviceDuplicated:(DeviceInfo *)deviceInfo
{
    for (DeviceInfo *tempDevice in self.deviceList)
    {
        if ([deviceInfo.did isEqualToString:tempDevice.did])
        {
            return YES;
        }
    }
    return NO;
}

#pragma -mark- Setter and Getter
- (NSMutableArray *)deviceList
{
    if (!_deviceList)
    {
        _deviceList = [NSMutableArray array];
    }
    return _deviceList;
}

- (LANFindServer *)lanFindServer
{
    if (nil == _lanFindServer)
    {
        _lanFindServer = [[LANFindServer alloc] init];
    }
    return _lanFindServer;
}

#pragma -mark- UITableViewDataSource

// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.deviceList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceCell_ID" forIndexPath:indexPath];
    
    DeviceInfo *deviceInfo = [self.deviceList objectAtIndex:indexPath.section];
    
    [cell.deviceName setText:deviceInfo.name];
    [cell.deviceUid setText:deviceInfo.did];
    
    [cell.alreadyAddedButton setHidden: deviceInfo.alreadyExist? NO: YES];
    [cell.notYetAddedButton setHidden:deviceInfo.alreadyExist? YES: NO];
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ([[UIScreen mainScreen] bounds].size.height - 61) / (float)5;
}




- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section != self.deviceList.count - 1) {
        return 3;
    }else{
        return 0.01f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 3)];
    footer.backgroundColor = [UIColor whiteColor];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 30;
    }else{
        return 0;
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    header.backgroundColor = rgba(201, 202, 203, 1);
    [self.view addSubview:header];
    UILabel *lable = [[UILabel alloc] init];
    [header addSubview:lable];
    lable.text = @"局域网中的设备";
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(header).offset(20);
        make.top.equalTo(header).offset(0);
        make.bottom.equalTo(header).offset(0);
        make.width.equalTo(@200);
    }];
    return header;
}





-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (0 == buttonIndex)
    {
        if (alertView.tag == FIND_DEVICE_ALERT)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else if(alertView.tag == NO_WIFI_ALERT)
        {
            BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
            if (canOpenSettings) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma -mark- UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DeviceInfo *deviceInfo = (DeviceInfo *)[self.deviceList objectAtIndex:indexPath.section];
    
    if ( deviceInfo.did == nil || deviceInfo.did.length == 0 ) {
        [SVProgressHUD showOnlyStatus:@"设备解析出错，设备ID为空" withDuration:2];
        return;
    }
    
    
    if (!deviceInfo.alreadyExist)
    {
        deviceInfo.indexPath = indexPath;
        //添加设备
        [self requestAddDevice:deviceInfo];
    }
    
    
}

//添加设备
- (void)requestAddDevice:(DeviceInfo *)deviceInfo{
    
    if (deviceInfo.did == nil || deviceInfo.did.length == 0) {
        [SVProgressHUD showOnlyStatus:@"设备解析出错，设备ID为空" withDuration:2];
        return;
    }
    deviceInfo.alreadyExist = YES;
    DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
    [deviceListVC addDevice:deviceInfo];
    [SVProgressHUD showSuccessWithStatus:@"添加成功" withDuration:1];
    [self.deviceList replaceObjectAtIndex:deviceInfo.indexPath.section withObject:deviceInfo];
    [self.tableView reloadData];
}



#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}



@end
